package forJava;

/**
 * @author hanj.cn@outlook.com
 */
public class HashCodeTest {

    public static void main(String[] args) {
        // 由于hashCode()的碰撞，同一个对象被误判为不相同，所以equal()和hashCode()方法都需要重写
        for (int i = 0; i < 20; i++) {
            Person p1 = new Person();
            p1.setAge(10);
            p1.setName("hanj");
            if (p1.hashCode() == p1.hashCode()) {
                System.out.println("是同一个对象");
            } else {
                System.out.println("不是同一个对象");
            }
        }

    }

}

class Person {

    private int age;
    private String name;

    @Override
    public int hashCode() {
        // 模拟会发生碰撞的hash算法
        return (int) (age + Math.random() * (3 - 1) + 1);
    }

    @Override
    public boolean equals(Object obj) {

        if (obj == null) {
            return false;
        } else {
            return this == obj;
        }
    }

    public int getAge() {

        return age;
    }

    public void setAge(int age) {

        this.age = age;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

}
